use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufRead};

// 读取简繁对照表
fn load_char_conversion_table(file_path: &str) -> (HashMap<char, char>, HashMap<char, char>) {
    let mut s2t_map = HashMap::new(); // 简体转繁体
    let mut t2s_map = HashMap::new(); // 繁体转简体
    let file = File::open(file_path).expect("file not found");
    let reader = io::BufReader::new(file);

    for line in reader.lines() {
        let line = line.expect("read line error");
        let parts: Vec<&str> = line
            .split(|c| c == '\t' || c == ' ')
            .filter(|s| !s.is_empty())
            .collect();
        if parts.len() < 2 {
            continue;
        }
        // 如果每个词都是单字符，进行转换
        if parts[0].chars().count() == 1 && parts[1].chars().count() == 1 {
            let simple_char = parts[0].chars().next().unwrap();
            let traditional_char = parts[1].chars().next().unwrap();
            // 单字符的简繁转换
            s2t_map.insert(simple_char, traditional_char);
            t2s_map.insert(traditional_char, simple_char);
        } else if parts.len() > 2 {
            // 处理多个繁体字对应的情况
            if parts[0].chars().count() == 1 {
                let simple_char = parts[0].chars().next().unwrap();
                for i in 1..parts.len() {
                    if parts[i].chars().count() == 1 {
                        let traditional_char = parts[i].chars().next().unwrap();
                        t2s_map.insert(traditional_char, simple_char);
                    }
                }
            }
        }
    }

    (s2t_map, t2s_map)
}
fn load_words_conversion_table(file_path: &str) -> io::Result<Trie> {
    let mut trie = Trie::new();
    let file = File::open(file_path)?;
    let reader = io::BufReader::new(file);

    for line in reader.lines() {
        let line = line?;
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() == 2 {
            let simplified = parts[0];
            let traditional = parts[1];
            trie.insert(simplified, traditional);
        } else {
            //只保存第一种繁体字
            let simplified = parts[0];
            let traditional = parts[1].split_whitespace().next().unwrap();
            trie.insert(simplified, traditional);
        }
    }
    Ok(trie)
}
// 转换函数
pub fn converter(input: &str, tp: &str) -> String {
    let (s2t_map, t2s_map) = load_char_conversion_table("STCharacters.txt");
    let trie = load_words_conversion_table("STPhrases.txt").expect("error");
    let mut ans = String::new();
    let input_chars: Vec<char> = input.chars().collect();

    if tp == "s2t" {
        let mut i = 0;
        while i < input_chars.len() {
            let mut matched = false;

            // 尝试匹配词
            for j in (i + 1..=input_chars.len()).rev() {
                let substring: String = input_chars[i..j].iter().collect();
                if let Some(traditional) = trie.search_longest_prefix(&substring) {
                    ans.push_str(&traditional);
                    i = j;
                    matched = true;
                    break;
                }
            }

            // 如果没有匹配到词，尝试匹配单个字符
            if !matched {
                let c = input_chars[i];
                if let Some(&traditional) = s2t_map.get(&c) {
                    ans.push(traditional);
                } else {
                    ans.push(c);
                }
                i += 1;
            }
        }
    } else if tp == "t2s" {
        for c in input_chars {
            if let Some(&simplified) = t2s_map.get(&c) {
                ans.push(simplified);
            } else {
                ans.push(c);
            }
        }
    } else {
        panic!("error input");
    }

    ans
}
#[derive(Debug)]
struct TrieNode {
    children: HashMap<char, TrieNode>,
    is_end: bool,
    traditional_word: Option<String>,
}

#[derive(Debug)]
struct Trie {
    root: TrieNode,
}

impl Trie {
    fn new() -> Self {
        Trie {
            root: TrieNode {
                children: HashMap::new(),
                is_end: false,
                traditional_word: None,
            },
        }
    }

    fn insert(&mut self, simple_words: &str, traditional_words: &str) {
        let mut node = &mut self.root;
        for char in simple_words.chars() {
            node = node.children.entry(char).or_insert(TrieNode {
                children: HashMap::new(),
                is_end: false,
                traditional_word: None,
            });
        }
        node.is_end = true;
        node.traditional_word = Some(traditional_words.to_string());
    }

    fn search_longest_prefix(&self, simple_words: &str) -> Option<String> {
        let mut node = &self.root;
        let mut longest_traditional: Option<String> = None; // 保存最长匹配的繁体字
        for char in simple_words.chars() {
            if let Some(next_node) = node.children.get(&char) {
                println!("{:?}", next_node);
                node = next_node;
                if node.is_end {
                    // 更新匹配到的最长前缀及其对应的繁体字
                    if let Some(words) = &node.traditional_word {
                        longest_traditional = Some(words.to_string());
                    }
                }
            } else {
                break; // 如果无法继续匹配，结束搜索
            }
        }
        longest_traditional
    }
}
